package com.abou.mvc.validation.impl;

import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.abou.constant.product.EColor;
import com.abou.constant.product.EProductType;
import com.abou.model.common.product.Product;
import com.abou.mvc.validation.annotation.ProductColorValid;

/**
 * The validator used to check that a product object contains consistent values
 * 
 * @author khalid
 */
public class ColorValidConstraintValidator implements
    ConstraintValidator<ProductColorValid, Product> {
  
  /**
   * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
   */
  public void initialize(ProductColorValid annotation) {

  }
  
  /**
   * @see javax.validation.ConstraintValidator#isValid(java.lang.Object,
   *      javax.validation.ConstraintValidatorContext)
   */
  public boolean isValid(Product product, ConstraintValidatorContext context) {

    boolean isValid = true;
    EProductType type = product.getProductType();
    List<EColor> colors = product.getColors();
    
    if ((type == EProductType.CLOTHING_BOY
        || type == EProductType.CLOTHING_GIRL
        || type == EProductType.CLOTHING_MAN || type == EProductType.CLOTHING_WOMAN)
        && (colors == null || colors.size() < 1)) {
      
      ConstraintValidatorContext.ConstraintViolationBuilder builder =
          context.buildConstraintViolationWithTemplate("");
      builder.addNode("colors").addConstraintViolation();
      
      isValid = false;
    }
    
    System.out.println("type => " + type + " " + colors);
    
    return isValid;
  }
}
